<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预约时间">
        <el-date-picker
          v-model="daterangeRegistTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="预约渠道" prop="appointmentWay">
        <el-select v-model="queryParams.appointmentWay" placeholder="请选择预约渠道" clearable>
          <el-option
            v-for="dict in dict.type.user_channel_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否登记" prop="registStatus">
        <el-select v-model="queryParams.registStatus" placeholder="请选择是否登记" clearable>
          <el-option label="未登记" :value="0" />
          <el-option label="已登记" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否作废" prop="del">
        <el-select v-model="queryParams.del" placeholder="请选择是否作废" clearable>
          <el-option label="未作废" :value="0" />
          <el-option label="已作废" :value="1" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="yuyueList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="预约状态" align="center" width="90" prop="registStatus">
        <template slot-scope="scope">
          <span>{{ scope.row.registStatus == 0 ? '未登记' : '正常登记' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否作废" align="center" width="90" prop="del">
        <template slot-scope="scope">
          <span>{{ scope.row.del == 0 ? '-' : '√' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="预约时间" align="center" prop="registTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="就诊卡号" align="center" width="130" prop="clinicCard"/>
      <el-table-column label="姓名" align="center" prop="name"/>
      <el-table-column label="年龄" align="center" prop="age"/>
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="img" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.img" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" width="130" prop="phone"/>

      <el-table-column label="挂号诊费" align="center" prop="medicalFee"/>
      <el-table-column label="预约渠道" align="center" width="90" prop="appointmentWay">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user_channel_status" :value="scope.row.appointmentWay"/>
        </template>
      </el-table-column>
      <el-table-column label="预约科室" align="center" prop="department.name"/>
      <el-table-column label="预约医生" align="center" prop="doctor.name"/>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.del !== 1"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['register:yuyue:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.del !== 1"
            @click="toggleRegistration(scope.row)"
          >
            {{ scope.row.registStatus == 0 ? '登记' : '取消登记' }}
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['register:yuyue:remove']"
          >
            {{ scope.row.del == 0 ? '作废' : '' }}
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 第一行: 预约时间和就诊科室 -->
        <el-row :gutter="20">
          <!-- 第一行: 预约时间和就诊卡号 -->
          <el-col :span="12">
            <el-form-item label="预约时间" prop="registTime">
              <el-date-picker
                clearable
                v-model="form.registTime"
                type="date"
                :picker-options="pickerOptions0"
                value-format="yyyy-MM-dd"
                placeholder="请选择预约时间"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="就诊卡号" prop="clinicCard">
              <el-input v-model="form.clinicCard" placeholder="请输入就诊卡号"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="就诊科室" prop="departmentId">
              <el-select v-model="form.departmentId" placeholder="请选择科室">
                <el-option v-for="item in departmentList" :key="item.id" :label="item.name" :value="item.id">
                  {{ item.name }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="就诊医生" prop="doctorId">
              <el-select v-model="form.doctorId" placeholder="请选择医生">
                <el-option v-for="item in doctorList" :key="item.id" :label="item.name" :value="item.id"
                           v-if="item.departmentId == form.departmentId">
                  {{ item.name }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行: 就诊姓名和就诊性别 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.value">{{
                    dict.label
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行: 身份证号和就诊年龄 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="identityCard">
              <el-input v-model="form.identityCard" placeholder="请输入身份证号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="form.age" controls-position="right" :min="0" :max="150" style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行: 手机号码和所属民族 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属民族" prop="nation">
              <el-select v-model="form.nation" placeholder="请选择所属民族" clearable>
                <el-option
                  v-for="dict in dict.type.people_ethnic_ffiliation"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>

        <!-- 第六行: 联系地址 -->
        <el-form-item label="联系地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入联系地址"/>
        </el-form-item>
        <el-form-item label="预约渠道" prop="appointmentWay">
          <el-radio-group v-model="form.appointmentWay">
            <el-radio v-for="dict in dict.type.user_channel_status" :key="dict.value" :label="dict.value">
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <image-upload v-model="form.img"/>
        </el-form-item>

        <!-- 第七行: 门诊编号和住院编号 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门诊编号" prop="outpatientId">
              <el-input v-model="form.outpatientId" placeholder="请输入门诊编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="住院编号" prop="admissionId">
              <el-input v-model="form.admissionId" placeholder="请输入住院编号"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第八行: 医保性质和医保卡号 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医保性质" prop="nature">
              <el-input v-model="form.nature" placeholder="请输入医保性质"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医保卡号" prop="cardnumber">
              <el-input v-model="form.cardnumber" placeholder="请输入医保卡号"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" @click="submitForm">保存挂号</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listYuyue, getYuyue, delYuyue, addYuyue, updateYuyue, getDepartmentList, getDoctorList, delCostByParentId, delConsultationByRegisterId,addConsultation} from "@/api/register/yuyue";

export default {
  name: "Yuyue",
  dicts: ['people_ethnic_ffiliation', 'user_channel_status', 'sys_yes_no', 'sys_user_sex'],
  data() {
    return {
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;//如果没有后面的-8.64e7就是不可以选择今天的
        }
      },
      doctorList: [],
      departmentList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预约表格数据
      yuyueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 预约医生时间范围
      daterangeRegistTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        registTime: null,
        name: null,
        phone: null,
        isCancel: null,
        appointmentWay: null,
        departmentId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        registTime: [
          {required: true, message: "预约时间不能为空", trigger: "blur"}
        ],
        department: [
          {required: true, message: "就诊科室不能为空", trigger: "change"}
        ],
        doctorId: [
          {required: true, message: "就诊医生不能为空", trigger: "change"}
        ],
        clinicCard: [
          {required: true, message: "就诊卡号不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "姓名不能为空", trigger: "blur"}
        ],
        identityCard: [
          {required: true, message: "身份证号不能为空", trigger: "blur"}
        ],
        age: [
          {required: true, message: "年龄不能为空", trigger: "blur"}
        ],
        sex: [
          {required: true, message: "性别不能为空", trigger: "change"}
        ],
        phone: [
          {required: true, message: "手机号码不能为空", trigger: "blur"}
        ],
        nation: [
          {required: true, message: "民族不能为空", trigger: "change"}
        ],
        address: [
          {required: true, message: "联系地址不能为空", trigger: "blur"}
        ],
        appointmentWay: [
          {required: true, message: "预约渠道不能为空", trigger: "change"}
        ],
        departmentId: [
          {required: true, message: "预约科室不能为空", trigger: "change"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDepartmentList();
    this.getDoctorList();
  },
  methods: {
      disabledDate(date) {
        return date < new Date().setHours(0, 0, 0, 0); // 禁止选择今天之前的日期
      },
      // 处理登记和取消登记操作
      toggleRegistration(row) {
        const newStatus = row.registStatus == 0 ? 1 : 0;
        const registerId = row.id;

        // 更新预约状态
        this.updateStatusAndHandleConsultation(registerId, newStatus)
          .then(() => {
            row.registStatus = newStatus; // 更新表格中的数据
          })
          .catch(() => {
            this.$modal.msgError("操作失败");
          });
      },

      // 更新登记状态并处理问诊
      updateStatusAndHandleConsultation(registerId, registStatus) {
        return updateYuyue({ id: registerId, registStatus })
          .then(() => {
            if (registStatus === 1) {
              // 如果是登记，新增问诊
              const costConsultation = {
                status: 1,
                inquiryId: 1000 + registerId,
                registerId,
                inquiryTime: new Date(), // 假设使用当前时间作为问诊时间
              };
              return addConsultation(costConsultation)
                .then(() => {
                  this.$modal.msgSuccess("登记成功，并新增问诊成功");
                })
                .catch(() => {
                  this.$modal.msgWarning("登记成功，但新增问诊失败");
                });
            } else if (registStatus === 0) {
              // 如果是取消登记，删除问诊
              return delConsultationByRegisterId([registerId])
                .then(() => {
                  this.$modal.msgSuccess("取消登记成功，并删除问诊成功");
                })
                .catch(() => {
                  this.$modal.msgWarning("取消登记成功，但删除问诊失败");
                });
            }
          })
          .finally(() => {
            this.getList(); // 刷新表格数据
          });
      },
    getDoctorList() {
      getDoctorList().then(response => {
        this.doctorList = response.rows;
      })
    },
    getDepartmentList() {
      getDepartmentList().then(response => {
        this.departmentList = response.rows;
      });
    },
    /** 查询预约列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeRegistTime && '' != this.daterangeRegistTime) {
        this.queryParams.params["beginRegistTime"] = this.daterangeRegistTime[0];
        this.queryParams.params["endRegistTime"] = this.daterangeRegistTime[1];
      }
      listYuyue(this.queryParams).then(response => {
        this.yuyueList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        registStatus: null,
        registTime: null,
        clinicCard: null,
        name: null,
        identityCard: null,
        age: null,
        sex: null,
        img: null,
        phone: null,
        nation: null,
        address: null,
        outpatientId: null,
        medicalhistory: null,
        admissionId: null,
        nature: null,
        cardnumber: null,
        isCancel: null,
        medicalFee: null,
        appointmentWay: null,
        departmentId: null,
        doctorId: null,
        del: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getDepartmentList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeRegistTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加预约";
      this.getDepartmentList();
      this.getDoctorList();
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getYuyue(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改预约";
        this.getDepartmentList();
        this.getDoctorList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateYuyue(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addYuyue(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const registStatus = row.registStatus;
      this.$modal.confirm('是否确认作废预约编号为"' + ids + '"的数据项？,此结果不可逆!').then(function () {
        return delYuyue(ids)
          .then(()=>{
            if(registStatus!=0){
            return  delConsultationByRegisterId(ids);
            }
          })
          .then(() => delCostByParentId(ids));
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("作废成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('register/yuyue/export', {
        ...this.queryParams
      }, `yuyue_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
